package com.elitesland.demo.config;

import com.elitesland.security.config.bean.JwtProperties;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Objects;

/**
 * swagger配置.
 * <p>
 * knife4j.production = false时生效
 *
 * @author Kaiser（wang shao）
 * @date 2021-01-27
 */
@Configuration
@ConditionalOnProperty(prefix = "knife4j", name = "production", havingValue = "false")
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {

    private static final Logger logger = LoggerFactory.getLogger(SwaggerConfig.class);

    /**
     * 标题
     */
    @Value("${swagger.title}")
    private String title;
    /**
     * 描述
     */
    @Value("${swagger.description}")
    private String description;
    /**
     * URL
     */
    @Value("${swagger.url}")
    private String url;
    /**
     * 作者
     */
    @Value("${swagger.contact.name}")
    private String contactName;
    /**
     * 作者网址
     */
    @Value("${swagger.contact.url}")
    private String contactUrl;
    /**
     * 作者邮箱
     */
    @Value("${swagger.contact.email}")
    private String contactEmail;
    /**
     * 版本
     */
    @Value("${swagger.version}")
    private String version;

    private final JwtProperties jwtProperties;
    private final OpenApiExtensionResolver openApiExtensionResolver;
    private final ServerProperties serverProperties;

    public SwaggerConfig(JwtProperties jwtProperties, OpenApiExtensionResolver openApiExtensionResolver, ServerProperties serverProperties) {
        this.jwtProperties = jwtProperties;
        this.openApiExtensionResolver = openApiExtensionResolver;
        this.serverProperties = serverProperties;
    }

    @Bean
    public Docket createBackendRestApi() {
        String groupName = "管理端接口API";
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .apiInfo(apiInfo(groupName))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.elitesland.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(List.of(parameterHeaderToken(jwtProperties.getHeader(), 0)))
                .extensions(openApiExtensionResolver.buildExtensions(groupName))
                ;
    }

    @Bean
    public Docket createAppletRestApi() {
        String groupName = "移动端接口API";
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .apiInfo(apiInfo(groupName))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.elitesland.demo.controller.app"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(List.of(parameterHeaderToken("Access-Token", 0)))
                .extensions(openApiExtensionResolver.buildExtensions(groupName))
                ;
    }

    private ApiInfo apiInfo(String desc) {
        return new ApiInfoBuilder()
                .title(title)
                .description(description + "【" + desc + "】")
                .termsOfServiceUrl(getServiceUrl())
                .contact(new Contact(contactName, contactUrl, contactEmail))
                .version(version)
                .build();
    }

    private Parameter parameterHeaderToken(String name, Integer order) {
        return new ParameterBuilder().name(name)
                .parameterType("header")
                .modelRef(new ModelRef("String"))
                .order(order)
                .description("用户token")
                .build();
    }

    private String getServiceUrl() {
        if (StringUtils.isNotBlank(url)) {
            return url;
        }
        int port = Objects.requireNonNullElse(serverProperties.getPort(), 8080);
//        String contextPath = StringUtils.defaultIfBlank(serverProperties.getServlet().getContextPath(), "");
        return "http://" + getIp() + ":" + port;
    }

    private String getIp() {
        if (serverProperties.getAddress() != null) {
            return serverProperties.getAddress().getHostAddress();
        }
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取服务器IP失败", e);
        }
        return "127.0.0.1";
    }
}
